﻿using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
using System;

namespace DataCapture.Helper
{
    public class JsonHelper
    {
        private readonly string _configFilePath;
        private static Dictionary<string, string> _connectionStrings;

        private static readonly Lazy<JsonHelper> instance = new Lazy<JsonHelper>(() => new JsonHelper());
        public static JsonHelper Instance => instance.Value;
        
        public JsonHelper()
        {
            try
            {
                string basePath = AppDomain.CurrentDomain.BaseDirectory;
                string configFileName = "PlcConfig.json";//plc配置文件名
                string configFilePath = Path.Combine(basePath, configFileName);
                //确定指定文件是否存在
                if (!File.Exists(configFilePath))
                {
                    throw new FileNotFoundException("配置文件未找到", configFilePath);
                }
                //读取Json文件的所有文本内容
                string jsonContent = File.ReadAllText(configFilePath);
                 PublicHelp.PlcDataList = JsonConvert.DeserializeObject<List<PublicHelp.PlcData>>(jsonContent);
            }
            catch (IOException ioEx)
            {
                throw new Exception($"访问配置文件时出错: {ioEx.Message}", ioEx);
            }
            catch (JsonReaderException jsonEx)
            {
                throw new Exception($"将配置文件解析为JSON时出错: {jsonEx.Message}", jsonEx);
            }
        }

        /// <summary>
        /// 读取字段值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConnectionString(string key)
        {
            _connectionStrings.TryGetValue(key, out string connectionString);
            return connectionString;
        }

        /// <summary>
        /// 添加或更新字段值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public void AddOrUpdateConnectionString(string key, string value)
        {
            _connectionStrings[key] = value;
            try
            {
                Save();
            }
            catch (Exception ex)
            { 
                Console.WriteLine($"保存配置时发生错误: {ex.Message}");
                throw;
            }
        }
        private void Save()
        {
            try
            {
                string directory = Path.GetDirectoryName(_configFilePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string jsonContent = JsonConvert.SerializeObject(_connectionStrings, Formatting.Indented);
                File.WriteAllText(_configFilePath, jsonContent);
            }
            catch (IOException ioEx)
            {
                throw new Exception($"写入配置文件时出错: {ioEx.Message}", ioEx);
            }
            catch (JsonWriterException jsonEx)
            {
                throw new Exception($"将配置序列化为JSON时出错: {jsonEx.Message}", jsonEx);
            }
        }
    }
}
